package cn.code.mycloud.module.system.service.grid;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.code.mycloud.module.system.controller.admin.grid.vo.*;
import cn.code.mycloud.module.system.dal.dataobject.grid.GridDO;
import cn.code.mycloud.framework.common.pojo.PageResult;
import cn.code.mycloud.framework.common.pojo.PageParam;
import cn.code.mycloud.framework.common.util.object.BeanUtils;

import cn.code.mycloud.module.system.dal.mysql.grid.GridMapper;

import static cn.code.mycloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.code.mycloud.module.system.enums.ErrorCodeConstants.*;

/**
 * 网格 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class GridServiceImpl implements GridService {

    @Resource
    private GridMapper gridMapper;

    @Override
    public Long createGrid(GridSaveReqVO createReqVO) {
        // 插入
        GridDO grid = BeanUtils.toBean(createReqVO, GridDO.class);
        gridMapper.insert(grid);
        // 返回
        return grid.getId();
    }

    @Override
    public void updateGrid(GridSaveReqVO updateReqVO) {
        // 校验存在
        validateGridExists(updateReqVO.getId());
        // 更新
        GridDO updateObj = BeanUtils.toBean(updateReqVO, GridDO.class);
        gridMapper.updateById(updateObj);
    }

    @Override
    public void deleteGrid(Long id) {
        // 校验存在
        validateGridExists(id);
        // 删除
        gridMapper.deleteById(id);
    }

    private void validateGridExists(Long id) {
        if (gridMapper.selectById(id) == null) {
            throw exception(GRID_NOT_EXISTS);
        }
    }

    @Override
    public GridDO getGrid(Long id) {
        return gridMapper.selectById(id);
    }

    @Override
    public PageResult<GridDO> getGridPage(GridPageReqVO pageReqVO) {
        return gridMapper.selectPage(pageReqVO);
    }

    @Override
    public List<GridDO> selectAll() {
        return gridMapper.selectList();
    }

}